<template>
<h1>登录页面</h1>
  <el-card style="width: 500px;height: 260px;margin: 0 auto">
    <el-form label-width="100px">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input placeholder="请输入密码" type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item><el-button @click="login()">登录</el-button></el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
  import {ref} from "vue";
  import qs from "qs";
  import axios from "axios";
  import {ElMessage} from "element-plus";
  import router from "@/router";
  const user = ref({username:"",password:""});
  const login = ()=>{
    //将js对象转成查询字符串格式
    let data = qs.stringify(user.value);
    //发出登录请求
    axios.post('http://localhost:8080/v1/users/login',data)
    .then((response)=>{
      if (response.data.code==2001){
        let user = response.data.data;
        //localStorage里面只能保存字符串类型的数据 user是JS对象
        //JSON.stringify(user) 将user对象转成JSON格式的字符串
        localStorage.setItem('user',JSON.stringify(user));
        ElMessage.success("登录成功!欢迎"+user.nickname+"回来!");
        router.push('/');
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
</script>

<style scoped>

</style>